﻿using System;
using System.IO;
using System.IO.Packaging;
using System.Web.UI;
using Microsoft.SharePoint;
using OfficeOpenXml;

namespace Eneta.Portal.UiActions.Pages
{
    public class DownloadAsExcel : Page
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var listGuid = new Guid(Request.QueryString["list"]);
            var list = SPContext.Current.Web.Lists[listGuid];
            if (list == null)
            {
                Response.Write("Cannot find list ");
                return;
            }

            var view = list.Views[new Guid(Request.QueryString["view"])];
            var items = list.GetItems(view);
            var fileInfo = new FileInfo(Path.GetTempPath()+"\\" + DateTime.Now.Ticks + ".xlsx");
            try
            {
                using (var xls = new ExcelPackage(fileInfo))
                {
                    var sheet = xls.Workbook.Worksheets.Add(list.Title);
                    
                    for (var i = 0; i < view.ViewFields.Count; i++)
                    {
                        sheet.Cell(1, 1 + i).Value = view.ViewFields[i];
                    }
                    var j = 1;
                    foreach (SPListItem item in items)
                    {
                        j++;
                        for (var i = 0; i < view.ViewFields.Count; i++)
                        {
                            if (item[view.ViewFields[i]] != null)
                            {
                                var field = item.Fields.GetFieldByInternalName(view.ViewFields[i]);
                                if(field.Type == SPFieldType.User)
                                {
                                    var usr = new SPFieldUserValue(list.ParentWeb, item[view.ViewFields[i]].ToString());
                                    sheet.Cell(j, 1 + i).Value = usr.LookupValue;
                                }
                                else if(field.Type == SPFieldType.URL)
                                {
                                    var link = new SPFieldUrlValue(item[field.Id].ToString());
                                    sheet.Cell(j, 1 + i).Value = link.Url;
                                    sheet.Cell(j, 1 + i).Hyperlink = new Uri(link.Url);
                                }
                                else
                                {
                                    sheet.Cell(j, 1 + i).Value = item[view.ViewFields[i]].ToString();
                                }
                            }
                            else
                                sheet.Cell(j, 1 + i).Value = string.Empty;
                        }
                    }

                    xls.Save();                    
                }
                Response.Clear();
                Response.ContentType = "application/vnd.openxmlformats";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
                Response.WriteFile(fileInfo.FullName);
                Response.Flush();

                if (fileInfo.Exists)
                    fileInfo.Delete();
            }
            catch(Exception ex)
            {
                Response.Write("VIGA::: ");
                Response.Write(ex);
            }
            Response.End();
            return;
            Response.Clear();
            Response.ContentType = "text/plain; charset=utf-8";
            Response.AddHeader("Content-disposition", "attachment; filename=results.csv");
            Response.AddHeader("Content-disposition", "attachment; filename=results.csv");


//            Response.Write(@"<?xml version=""1.0""?>
//                             <?mso-application progid=""Excel.Sheet""?>
//                             <Workbook xmlns=""urn:schemas-microsoft-com:office:spreadsheet""
//                                xmlns:o=""urn:schemas-microsoft-com:office:office""
//                                xmlns:x=""urn:schemas-microsoft-com:office:excel""
//                                xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet""
//                                xmlns:html=""http://www.w3.org/TR/REC-html40"">\r\n
//                            <Worksheet ss:Name=""Results"">
//                            <Table>");
            
            for(var i = 0; i<view.ViewFields.Count; i++)
            {
                Response.Write(view.ViewFields[i]);
                if(i<view.ViewFields.Count -1 )
                {
                    Response.Write(";");
                }
            }
            Response.Write("\r\n");

            foreach (SPListItem item in items)
            {
                for (var i = 0; i < view.ViewFields.Count; i++)
                {
                    Response.Write(item[view.ViewFields[i]]);
                    if (i < view.ViewFields.Count - 1)
                    {
                        Response.Write(";");
                    }
                }

                Response.Write("\r\n");
            }
            
            //Response.Write("</Table></Worksheet></Workbook>");
            Response.Flush();
            Response.End();
        }
    }
}
